package com.wanxi.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.wanxi.dto.ResultDto;
import com.wanxi.model.UserModel;
import com.wanxi.service.Impl.UserServiceImpl;
import com.wanxi.service.UserService;
import com.wanxi.util.MD5;
import com.wanxi.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Li
 * @Date 2023/5/3 21:42
 */
@WebServlet("/back/AddUser")
public class UserAddServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //2.接收前端数据
    String username = req.getParameter("username");
    String password = req.getParameter("password");
    String age = req.getParameter("age");
    String sex = req.getParameter("sex");
    String phone = req.getParameter("phone");
    String email = req.getParameter("email");
    String address = req.getParameter("address");
    String enable = req.getParameter("enable");
    String remark = req.getParameter("remark");
        //3.封装数据
   UserModel model =  UserModel.builder()
           .username(Tool.nullToStr(username))
           .password(MD5.encoderByMd5(password))
           .age(Tool.nullToInt(age))
           .sex(Tool.nullToStr(sex))
           .phone(Tool.nullToStr(phone))
           .email(Tool.nullToStr(email))
           .address(Tool.nullToStr(address))
           .enable(Tool.nullToInt(enable))
           .remark(Tool.nullToStr(remark))
           .build();
   //4.调用服务逻辑层
        UserService userService = new UserServiceImpl();
        ResultDto resultDto = userService.add(model);
        //数据转发给前端：IO流方式
//        数据格式使用JSON对象,引入第三方jar包，fastJson
       resp.getWriter().println(JSONObject.toJSONString(resultDto));
    }
}
